/*
 * commhand.c
 *
 *  Created on: Sep 4, 2013
 *      Author: Alex Bouvy
 */

#include <string.h>
#include <stdio.h>
#include <ctype.h>

int commhand() {
	char prompt[3] = "$$>";

	//------------comm literals----------------
	char c1[3]="ls\0";
	char c2[5]="date\0";
	char c3[5]="exit\0";
	char c4[5]="help\0";
	char c5[8]="version\0";
	//------------/comm literals---------------

	char input[256];
	char* input_tok[6];
	int bufferSize = 256;
	int promptLength = 3;
	int gallop = 1; //set this horse to moving!
	int stringSize; //COMPILER IS NOT CORRECT, THIS VARIABLE IS USED
	int command_args=0;
	int max_args = 6;
	int i;
	//loop until user enters the exit command
	while(gallop) { //while still kicking up dust

		command_args=0;
		//print the prompt to the terminal
		promptLength = 3;
		sys_req(2,1, prompt, &promptLength);
		stringSize = sys_req(1, 1, input, &bufferSize);

		input_tok[0] = strtok(input," ");
		if(!strcmp(input_tok[0],"\n")){
			continue;
		}
		else{
			for(i=1;i<max_args;i++){
				input_tok[i]=strtok(NULL," ");
				if(input_tok[i]==NULL) break;
				else command_args = i;
			}
		}

		//hacky fix for tokenization
	        if(command_args==0){
	                strxfrm(input_tok[0],input_tok[0], strlen(input_tok[0]));
	                strcat(input_tok[0],"\0");
	        } 

		//hacky space for other tokenization issue
	        if(command_args==1){
	                if(!(strcmp(input_tok[1],"\n"))){
	                        command_args=0;
	                        input_tok[1] = NULL;
	                }
	        }

		//error handling
		if(!(strcmp(input_tok[0],c1))) {
			if(command_args>0){
				printf("Command %s does not accept arguments.\n",c1);
			}
			else ls();
		}
		else if(!(strcmp(input_tok[0],c2))){
			date(input_tok, command_args);
		}
		else if(!(strcmp(input_tok[0],c3))) {
			if(command_args>0){
				printf("Command %s does not accept arguments.\n",c3);
			}
			else r_exit(&gallop);
		}
		else if(!(strcmp(input_tok[0],c4))) {
			help(command_args, input_tok);
		}
		else if(!(strcmp(input_tok[0],c5))) {
			if(command_args>0){
				printf("Command %s does not accept arguments.\n",c5);
			}
			else version();
		}
		else printf("Command '%s' not recognized\n",input_tok[0]);
	}
	return 0;
}
